<?php
/**
 * 前台文章模型
 * 结合关联模型
 */
import('RelationModel');
class ArticleModel extends RelationModel{

  /**
   * 与评论,栏目,标签关联定义
   */
  protected $_link=array(
	 'Category'=>array(
	   'mapping_type'=>BELONGS_TO,
	   'class_name'=>'Category',
	   'foreign_key'=>'category_id',
	   'mapping_name'=>'Category',
	   'mapping_fields'=>'title,id',

	 ),
	 'Tag'=>array(
	 	  'mapping_type'=>MANY_TO_MANY,
      'class_name'=>'Tag',
      'mapping_name'=>'Tags',
      'foreign_key'=>'value_id',
      'relation_foreign_key'=>'tag_id',
      'relation_table'=>'ke_tag_article'
     ),
   'Comment'=>array(
      'mapping_type'=>HAS_MANY,
      'class_name'=>'Comment',
      'mapping_name'=>'Comment',
      'foreign_key'=>'value_id',
      'condition'=>"source='Article' AND status=1",
      'mapping_fields'=>'count(id) as cmtNum'
     )   
  );

  /**
   * 根据推荐位置获取数据
   * @param int $flag index首页 channel频道 list列表 content内容页
   * @param int $thumb 0-无图 1-有图 默认无图
   * @param string $categoryId 栏目ID,指定多栏目结构为1,2,3 
   * @param int $num 显示数量 默认5
   * @return array 
   */
  public function getArticleListByFlag($flag,$thumb=0,$categoryId=0,$listRows=5)
  {
    if($categoryId!=0)$where['category_id']=array('in',$categoryId);
    if($thumb!=0)$where['thumb']=array('neq','');
    $where['flag']=$flag;
    $where['status']=1;
  	return $this->field('id,title,category_id,hit,brief,thumb,edit_time,comments')->where($where)->relation('Comment')->order('id DESC')->limit($listRows)->select();
  }

  /**
   * 根据栏目ID获取数据
   * @param int $id 栏目ID,指定多栏目结构为1,2,3 
   * @param int $thumb 0-无图 1-有图 默认无图 
   * @param int $listRows 显示数量 默认5
   * @return array 
   */
  public function getArticleListByCategory($id,$thumb=0,$listRows=5)
  {
    if(isset($id))$where['category_id']=array('in',$id);
    if($thumb!=0)$where['thumb']=array('neq','');
    $where['status']=1;
    return $this->field('id,title,category_id,hit,brief,thumb,edit_time,comments')->where($where)->relation('Comment')->order('id DESC')->limit($listRows)->select();
  }

  /**
   * 根据条件获取数据
   * @param array $where 条件数组
   * @param int $listRows 显示数量 默认5
   * @return array 
   */
  public function getArticleListByMap($where,$listRows=5,$firstRow=0,$order='id DESC')
  {
    $where['status']=1;
    return $this->field('id,title,category_id,hit,brief,thumb,edit_time,comments')->where($where)->relation('Comment')->order($order)->limit($firstRow.','.$listRows)->select();
  }

  /**
   * 随即获取数据
   * @param int $listRows 显示数量 默认5
   * @return array 
   */
  public function getArticleListByRandom($listRows=5)
  {
    $where['status']=1;
    return $this->field('id,title,category_id,hit,brief,thumb,edit_time,comments')->where($where)->relation('Comment')->order('RAND()')->limit($listRows)->select();
  }  

  /**
   * 归档统计
   * @return array 
   */
  public function getArticleByTime()
  {
    $where['status']=1;
    return $this->field('add_time,id,count(id) as total')->where($where)->group('add_time')->select();
  }      
   	
}
?>